// Copyright 2007 Google Australia
// All Rights Reserved.

/**
 * @fileoverview This package allows you to automatically apply _link to links that you have tagged as requiring this functionality. 
 * Tag the links by specifying a custom-defined style name in that link's class attribute
 * @author vinoaj@google.com (Vinoaj Vijeyakumaar)
 *
 * Usage:
 *  - Identify links with by taggig it with a consistent name in the link's style attribute (e.g. class="xyz")
 *  - The link can be identified even if a style has already been applied to the link (e.g. class="myStyle xyz myOtherStyle")
 *  - Call the below code after all links have been rendered on page (because the links will be pulled from the DOM) 
 * 	var xdl = new gaCrossDomainLinker('styleName');
 *	xdl._setTestMode(false); 	//optional
 *	xdl._setTracker(someTracker);	//reference to the tracker created in the GATC call
 * 	xdl._gaLinkLinks();
 */




/**
 * Class gaCrossDomainLinker
 * @param {string} classLabel The label that links will be tagged with and thus identified by
 * @constructor
 */
function gaCrossDomainLinker(classLabel) {
	this.classLabel = classLabel;
	this.testMode = false;
	this.tracker = null;
}

gaCrossDomainLinker.prototype._setTracker = function (tracker) {
	this.tracker = tracker;
}

gaCrossDomainLinker.prototype._setTestMode = function (bool) {
	this.testMode = bool;
}

gaCrossDomainLinker.prototype._gaLinkLinks = function() {
	//Collect all links on page
	var pageLinks = document.getElementsByTagName('a');
	
	//Check if any links are on this page
	//TODO: test
	var nLinks = pageLinks ? pageLinks.length : 0;
	if (nLinks < 1) {
		return true;
	}
	
	var testMode = this.testMode;
	var gaCDL = this;
	var re = new RegExp(this.classLabel, 'g');
	
	var nPageLinks = pageLinks.length;
	for (var l = 0; l < nPageLinks; l++) {
		var pageLink = pageLinks[l];
		//console.log(pageLink.className);
		
		if (pageLink.className && re.test(pageLink.className)) {
			//This is a labelled link - now action it
			pageLink.onclick = function() {
				var linkHref = pageLink.href;
				var test = testMode;

				//console.log('linkHref %s; testMode %s', pageLink.href, testMode);
				if (test) {
					alert('Clicking on labelled link: ' + linkHref);
				}
				
				gaCDL.tracker._link(linkHref);

				//Return false so the original link isn't followed
				return false;
			}
		}
	}
}
